<template>
  <div class="app-container">
    <el-form
      :model="formData"
      ref="form"
      size="small"
      label-position="right"
      :rules="rules"
      label-width="100px"
    >
      <!-- <el-form-item label="引用流程" prop="processDefinitionId">
        <el-cascader
          v-model="formData.processDefinitionId"
          :options="flowData"
          clearable
          filterable
          :show-all-levels="false"
          style="width: 40%"
          :props="{
            expandTrigger: 'click',
            multiple: false,
            checkStrictly: false,
            value: 'id',
            label: 'name',
          }"
          @change="onFlowChange"
        >
          <div slot-scope="{ node, data }" style="display: flex">
            <span style="min-width: 40%">{{ data.key }}</span>
            <span>{{ data.name }}</span>
          </div>
        </el-cascader>
        <el-descriptions :column="4">
          <el-descriptions-item label="流程标识">{{
            currFlow.key
          }}</el-descriptions-item>
          <el-descriptions-item label="表单信息">{{
            currFlow.description
          }}</el-descriptions-item>
          <el-descriptions-item label="流程版本">{{
            currFlow.version
          }}</el-descriptions-item>
          <el-descriptions-item label="部署时间">{{
            currFlow.publishTime
          }}</el-descriptions-item>
        </el-descriptions>
      </el-form-item> -->
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-form-item label="事项类型" prop="title">
            <el-radio-group v-model="formData.type">
              <el-radio :label="1">企业</el-radio>
              <el-radio :label="2">个人</el-radio>
              <el-radio :label="3">工作台</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="事项主题" prop="title">
            <el-input
              v-model="formData.title"
              placeholder="请输入事项主题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="起止日期" prop="endTime">
            <el-date-picker
              v-model="dateTime"
              style="width: 340px"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="事项内容" prop="content">
        <editor v-model="formData.content" :min-height="200" />
      </el-form-item>
      <el-form-item label="联系人信息" prop="contacts">
        <editor v-model="formData.contacts" :min-height="100" />
      </el-form-item>
      <el-form-item label="附件清单" prop="uploadPath">
        <file-upload v-model="fileList" :fileSize="20" :limit="20" />
      </el-form-item>

      <el-form-item label="流程" prop="sonList">
        <div
          v-for="(son, idx) in formData.sonList"
          class="corporate-son-process"
          :key="idx"
        >
          <el-input
            v-model="son.title"
            placeholder="请输入子流程事项主题"
            clearable
            @keyup.enter.native="handleQuery"
          />

          <el-select
            v-model="son.processMatter"
            placeholder="请选择子流程"
            clearable
            filterable
            @change="changeProcessEvent(son)"
          >
            <el-option
              v-for="item in flowData"
              :key="item.id"
              :label="`${item.key}  ${item.name}`"
              :value="`${item.id};${item.key}`"
            >
              <div style="display: flex">
                <span style="min-width: 40%">{{ item.key }}</span>
                <span>{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-minus"
            circle
            plain
            style="flex-shrink: 1; margin-left: 10px"
            @click="onDeleteProcess(son, idx)"
          ></el-button>
        </div>
        <el-button
          type="primary"
          circle
          size="mini"
          icon="el-icon-plus"
          plain
          @click="
            formData.sonList.push({
              enterpriseId: id,
              processMatter: '',
              title: '',
            })
          "
        ></el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Editor from "@/components/Editor";
import FileUpload from "@/components/FileUpload";
import {
  createEnterpriseInfo,
  updateEnterpriseInfo,
} from "@/api/enterprise/info";
import { getProcessDefinitionList } from "@/api/bpm/definition";
// import { getSimpleForms } from "@/api/bpm/form.js";
import {
  getNoticeDetail,
  getNoticeProcessList,
  deleteNoticeProcess,
} from "@/api/enterprise/info";

export default {
  components: { Editor, FileUpload },
  data() {
    const { id, officeId } = this.$route.query;
    return {
      id,
      officeId,
      formData: {
        id: id || undefined,
        processDefinitionId: [],
        title: "",
        startTime: "",
        endTime: "",
        content: "",
        status: "1",
        type: 1,
        sonList: [], // 绑定的多流程
        contacts: "", // 联系人
        uploadPath: "", // 附件，多个，逗号隔开
        uploadFilename: "", // 附件名称，多个，逗号隔开
      },
      fileList: [],
      dateTime: [], // 开始时间、结束时间
      // 事项状态选项
      rules: {
        processDefinitionId: [
          {
            required: true,
            message: "引用流程不能为空",
            trigger: "blur",
            type: "array",
          },
        ],
        title: [
          { required: true, message: "事项主题不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "起止日期不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "事项内容不能为空", trigger: "blur" },
        ],
        contacts: [
          { required: true, message: "联系人信息不能为空", trigger: "blur" },
        ],
        sonList: [
          { required: true, message: "流程绑定不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let hasEmpty = false;
              for (let i = 0; i < value.length; i++) {
                const item = value[i];
                if (!item.title || !item.processDefinitionId) {
                  hasEmpty = true;
                  break;
                }
              }
              if (hasEmpty) {
                callback(new Error("有子流程未填写完整，请检查并填写完毕"));
              } else {
                callback();
              }
            },
            trigger: "change",
            type: "string",
          },
        ],
      },
      flowData: [],
      /* currFlow: {
        description: "",
        version: "",
        publishTime: "",
      }, */
    };
  },
  watch: {
    fileList: {
      handler(val) {
        const uploadPath = [];
        const uploadFilename = [];
        for (let i = 0; i < val.length; i++) {
          const { name, url } = val[i];
          uploadPath.push(url);
          uploadFilename.push(name);
        }
        this.formData.uploadPath = uploadPath.join(",");
        this.formData.uploadFilename = uploadFilename.join(",");
      },
      deep: true,
    },

    dateTime: {
      handler(val) {
        if (val && val.length) {
          this.formData.startTime = this.parseTime(val[0]);
          this.formData.endTime = this.parseTime(val[1]);
        }
      },
      deep: true,
    },
  },
  created() {
    /* Promise.all([this.getFlowList(), this.getDetail()]).then(
      ([flowData, processDefinitionId]) => {
        if (flowData && flowData.length && processDefinitionId) {
          this.currFlow =
            flowData.filter(({ id }) => processDefinitionId == id)[0] || {};
        }
      }
    ); */
    this.getFlowList();
    this.getDetail();
    this.getProcessList();
  },
  methods: {
    /** 查询流程定义列表 */

    /** 查询流程定义列表 */
    async getFlowList() {
      const res = await getProcessDefinitionList({
        suspensionState: 1,
      });
      const flowData = res?.data || [];
      this.flowData = flowData;
      return flowData;
    },
    async getDetail() {
      if (this.id) {
        const { data } = await getNoticeDetail({ id: this.id });
        // if (data.type !== 1) {
        this.formData = {
          ...this.formData,
          ...(data || {}),
          /* processDefinitionId: data.processDefinitionId
            ? [data.processDefinitionId]
            : [], */
          type: data.type ? data.type : 1,
        };
        // 设置附件
        this.setFileList();
        this.setDateTime();
        // return data.processDefinitionId;
        // }
      }
      // return "";
    },
    setFileList() {
      const uploadPath = this.formData.uploadPath
        ? this.formData.uploadPath.split(",")
        : [];
      const uploadFilename = this.formData.uploadFilename
        ? this.formData.uploadFilename.split(",")
        : [];
      this.fileList = uploadPath.map((url, i) => ({
        url,
        name: uploadFilename[i] ? uploadFilename[i] : url,
      }));
    },
    setDateTime() {
      this.dateTime = [
        new Date(this.formData.startTime),
        new Date(this.formData.endTime),
      ];
    },

    async getProcessList() {
      if (this.id) {
        const { data } = await getNoticeProcessList(this.id);
        this.formData.sonList = data.map((item) => {
          item.processMatter = item.processDefinitionId + ";" + item.modelKey;
          return item;
        });
      }
    },
    onDeleteProcess({ id }, idx) {
      if (id) {
        deleteNoticeProcess(id).then(({ data }) => {
          if (data) {
            this.$message.success("删除成功");
            this.formData.sonList.splice(idx, 1);
          }
        });
      } else {
        // 新增的删除，不用提示
        this.formData.sonList.splice(idx, 1);
      }
    },
    changeProcessEvent() {
      this.formData.sonList = this.formData.sonList.map((item) => {
        let { processMatter } = item;
        item.processDefinitionId = processMatter.split(";")[0];
        item.modelKey = processMatter.split(";")[1];
        return item;
      });
    },
    /* onFlowChange([val]) {
      this.currFlow = this.flowData.filter(({ id }) => id === val)[0];
    }, */
    save() {
      const { processDefinitionId, ...rest } = this.formData;
      const params = {
        ...rest,
        processDefinitionId: processDefinitionId[0] || "",
      };
      this.$refs["form"].validate((valid) => {
        if (valid) {
          params.officeId = this.officeId;
          if (this.formData.id) {
            updateEnterpriseInfo(params).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.gotoList();
            });
          } else {
            createEnterpriseInfo(params).then((res) => {
              this.$modal.msgSuccess("新增成功");
              this.gotoList();
            });
          }
        }
      });
    },
    reset() {
      this.resetForm("form");
    },
    gotoList() {
      this.$router.replace("/corporate/items");
    },
  },
};
</script>

<style lang="scss">
.corporate-son-process {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  > *:not(.el-button) {
    width: 45%;
  }
}
</style>
